<?php

namespace app\common\service\OrderService;

use app\model\BbcModel\Channel;
use app\model\BbcModel\ChannelBusiness;
use app\model\BbcModel\Commission;
use app\model\BbcModel\ConfigChannel;
use app\model\BbcModel\MasterIncome;
use app\model\BbcModel\Order;
use app\model\BbcModel\OrderExtra;
use app\model\BbcModel\OrderGoods;
use app\model\BbcModel\OrderReturn;
use app\model\BbcModel\ServiceProvider;
use app\model\BbcModel\Store;
use app\model\BbcModel\PushAgain;
use app\model\BbcModel\StoreMember;
use app\model\BbcModel\BusinessMember;
use think\Facade\Db;
use app\Normal;
use app\model\BbcModel\OrderLog;
use app\model\BbcModel\Goods;


/**
 * 订单数据查询
 * @author linan
 */
class OrderCheckService
{

    /**
     * 组装查询条件
     * @param array $param
     * @return array
     */
    public function makeWhere(array $param)
    {
        $where=[];
        $where[]=['o.df','=',0];
        //服务商id
        if(!empty($param['sp_id'])){
            $where[]=['o.sp_id','=',$param['sp_id']];
        }
        //大Bid
        if(!empty($param['cid'])){
            $where[]=['o.cid','=',$param['cid']];
        }
        //渠道商id
        if(!empty($param['cb_id'])){
            $where[]=['o.cb_id','=',$param['cb_id']];
        }
        //店铺id
        if(!empty($param['mn_sid'])){
            $where[]=['o.mn_sid','=',$param['mn_sid']];
        }
        //登录用户
        if(!empty($param['mid'])){
            $where[]=['o.mid','=',$param['mid']];
        }
        //关键词
        if(!empty($param['key_word'])){
            $where[]=['o.sn|oe.express_num|oe.receive_name|oe.receive_mobile|oe.buyer_mobile|oe.buyer_name|oe.goods_name','like','%'.$param['key_word'].'%'];
        }
        //主订单号
        if(!empty($param['pay_sn'])){
            $where[]=['o.pay_sn','like','%'.$param['pay_sn'].'%'];
        }
        //子订单号
        if(!empty($param['sn'])){
            $where[]=['o.sn','like','%'.$param['sn'].'%'];
        }
        //下单时间
        if(!empty($param['cd_start'])){
            $where[]=['o.cd','>=',strtotime($param['cd_start'])];
        }
        if(!empty($param['cd_end'])){
            $where[]=['o.cd','<=',strtotime($param['cd_end'])];
        }
        //支付时间
        if(!empty($param['pay_start'])){
            $where[]=['o.pay_time','>=',strtotime($param['pay_start'])];
        }
        if(!empty($param['pay_end'])){
            $where[]=['o.pay_time','<=',strtotime($param['pay_end'])];
        }
        //发货时间
        if(!empty($param['shipping_start'])){
            $where[]=['o.shipping_time','>=',strtotime($param['shipping_start'])];
        }
        if(!empty($param['shipping_end'])){
            $where[]=['o.shipping_time','<=',strtotime($param['shipping_end'])];
        }
        //状态
        if(isset($param['status'])  && $param['status']!==''){
            $where[]=['o.status','=',$param['status']];
        }
        //是否售后
        if(isset($param['is_return'])  && $param['is_return']!==''){
            $where[]=['oe.is_return','=',$param['is_return']];
        }
        //超过24小时未发货
        if(isset($param['no_shipping'])  && $param['no_shipping']==1){
            $time=time()-86400;
            $where[]=['o.status','=',20];
            $where[]=['o.cd','<',$time];
        }
        //售后状态
        if(isset($param['return_status'])  && $param['return_status']!==''){
            $where[]=['oe.return_status','=',$param['return_status']];
        }
        //是否分佣
        if(isset($param['is_commission'])  && $param['is_commission']!==''){
            $where[]=['oe.is_commission','=',$param['is_commission']];
        }
        //服务商列表
        $service=ServiceProvider::instance()->lists(['_fields_'=>'id,name']);
        $service=array_column($service,'name','id');
        //渠道商列表
        $business=ChannelBusiness::instance()->lists(['_fields_'=>'id,name']);
        $business=array_column($business,'name','id');
        //店铺列表
        $store=Store::instance()->lists(['_fields_'=>'id,store_name']);
        $store=array_column($store,'store_name','id');
        return [
           'where'=>$where,
           'service'=>$service,
           'business'=>$business,
           'store'=>$store,
        ];
    }

    /**
     * 订单列表
     * @param array $param
     * @return array
     */
    public function orderList(array $param)
    {
        $this->noPayCancel();
//        $this->autoReceive();
        $check=$this->makeWhere($param);
        $page=(isset($param['page'])&&$param['page']>0)?$param['page']:1;
        $limit=(isset($param['limit'])&&$param['limit']>0)?$param['limit']:10;
        $p=($page-1)*$limit;
        $where=$check['where'];
        $service=$check['service'];
        $business=$check['business'];
        $store=$check['store'];
        $list=Order::instance()->alias('o')
            ->field('o.*,oe.*,oe.id as ex_id')
            ->join('order_extra oe','oe.order_id=o.id')
            ->where($where)
            ->limit($p, $limit)
            ->order('o.id', 'desc')
            ->select()
            ->toArray();
        $num=Order::instance()->alias('o')
            ->join('order_extra oe','oe.order_id=o.id')
            ->where($where)
            ->count();
        $data['total']=$num;
        foreach ($list as $k=>$v){
            $list[$k]['store_name']=$store[$v['mn_sid']]??'';
            $list[$k]['channel_name']=$business[$v['cb_id']];
            $list[$k]['service_name']=$service[$v['sp_id']];
            $list[$k]['status_name']=Order::instance()->status[$v['status']];
            $list[$k]['pay_type']=Order::instance()->pay_type[$v['pay_type']];
            $list[$k]['return_status_name']=Order::instance()->return_status[$v['return_status']];
            $list[$k]['cd']=$v['cd']>0?date('Y-m-d H:i:s',$v['cd']):'';
            $list[$k]['pay_time']=$v['pay_time']>0?date('Y-m-d H:i:s',$v['pay_time']):'';
            $list[$k]['shipping_time']=$v['shipping_time']>0?date('Y-m-d H:i:s',$v['shipping_time']):'';
            $list[$k]['receive_time']=$v['receive_time']>0?date('Y-m-d H:i:s',$v['receive_time']):'';
            $list[$k]['is_return']=$v['is_return']>0?'是':'否';
            $list[$k]['is_commission']=$v['is_return']>0?'是':'否';
            if( $v['push_success'] == 0 ) {
                $list[$k]['push_status'] = 1;
            } else {
                if($v['push_pay_success']==0 && $v['pay_status']==1){
                    $list[$k]['push_status'] =2;
                }else{
                    $list[$k]['push_status'] =0;
                }
            }
        }
        $data['list']=$list;
        return Normal::returnCode(Normal::SUC,"请求成功",$data);
    }

    /**
     * 订单详情
     * @param array $param
     * @return array
     */
    public function orderDetail(array $param)
    {
        if(empty($param['sn'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数sn");
        }
        $info=Order::instance()->alias('o')
            ->field('oe.*,o.*,oe.id as ex_id')
            ->leftJoin('order_extra oe','oe.order_id=o.id')
            ->where(['o.sn'=>$param['sn']])
            ->find();
        if(empty($info)){
            return Normal::returnCode(Normal::FAIL,"订单不存在");
        }
        $info['store_name']=Store::instance()->where(['id'=>$info['mn_sid']])->value('store_name');
        $info['business_name']=ChannelBusiness::instance()->where(['id'=>$info['cb_id']])->value('name');
        $info['service_name']=ServiceProvider::instance()->where(['id'=>$info['sp_id']])->value('name');
        $info['channel_name']=Channel::instance()->where(['id'=>$info['cid']])->value('business_name');
        $info['status_name']=Order::instance()->status[$info['status']];
        $info['pay_type']=Order::instance()->pay_type[$info['pay_type']];
        $info['return_status']=Order::instance()->return_status[$info['return_status']];
        $info['is_return']=$info['is_return']>0?'是':'否';
        $info['is_commission']=$info['is_return']>0?'是':'否';
        $info['cd']=$info['cd']>0?date('Y-m-d H:i:s',$info['cd']):'';
        $info['pay_time']=$info['pay_time']>0?date('Y-m-d H:i:s',$info['pay_time']):'';
        $info['shipping_time']=$info['shipping_time']>0?date('Y-m-d H:i:s',$info['shipping_time']):'';
        $info['receive_time']=$info['receive_time']>0?date('Y-m-d H:i:s',$info['receive_time']):'';
        $info['is_bonded_name']= Goods::instance()->is_bonded[$info['is_bonded']];
        $goods=OrderGoods::instance()->lists(['order_id'=>$info['id'],'_fields_'=>'goods_name,skucode,barcode,is_bonded,price_total,spec_num,num,price_pay,price_tax,price_express,price']);
        foreach ($goods as &$item) {
            $item['is_bonded_name']= Goods::instance()->is_bonded[$item['is_bonded']];
            unset($item);
        }
        $info['goods']=$goods;
        $orderlog= OrderLog::instance()->lists(['order_id'=>$info['id'],'_fields_'=>'','_order_'=>'id desc']);
        $info['order_log']=$orderlog;
        return Normal::returnCode(Normal::SUC,"请求成功",$info);
    }


    /**
     * 重新推单至云仓
     * @param array $param
     * @return array
     */
    public function pushAgain(array $param)
    {
        if(empty($param['sn'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数sn");
        }
        $order=Order::instance()->info(['sn'=>$param['sn']]);
        if(empty($order)){
            return Normal::returnCode(Normal::FAIL,"订单不存在");
        }
        if($order['status']==0){
            return Normal::returnCode(Normal::FAIL,"订单已取消");
        }
        //组装推送数据
        $data = PushAgain::instance()->info(['sn' => $param['sn']]);
        if(empty($data)){
            return Normal::returnCode(Normal::FAIL,"推送数据不存在");
        }
        $syncData = json_decode($data['order_data'], true);
        $OrderCloudService=new OrderCloudService();
        $res = $OrderCloudService->sendToStoB($syncData, 'createOrder');
        if ($res['code'] != 200) {
            return Normal::returnCode(Normal::FAIL,$res['msg']);
        } else {
            Order::instance()->edit(['id' => $order['id']], ['push_success' => 1]);
            $returnData = $res['data']['orderItems'];
            foreach ($returnData as $v) {
                OrderExtra::instance()->edit(['order_id' => $order['id']], ['stb_sn' => $v['orderNo']]);
            }
            if ($order['status'] == 20 && $order['pay_status'] == 1) {
                $orderData=json_decode($data['pay_data'], true);
                $res2 = $OrderCloudService->sendToStoB($orderData, 'OrderPay');
                if ($res2['code'] != 200) {
                    return Normal::returnCode(Normal::FAIL,'订单推送成功，但是云仓支付失败，失败原因：' . $res2['msg'] . ',请联系客服');
                }else{
                    Order::instance()->edit(['id' => $order['id']], ['push_pay_success' => 1]);
                }
            }
            return Normal::returnCode(Normal::SUC,'推送成功');
        }
    }

    /**
     * 重新支付至云仓
     * @param array $param
     * @return array
     */
    public function pushPayAgain(array $param)
    {
        if(empty($param['sn'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数sn");
        }
        $order=Order::instance()->info(['sn'=>$param['sn']]);
        if(empty($order)){
            return Normal::returnCode(Normal::FAIL,"订单不存在");
        }
        if($order['status']==0){
            return Normal::returnCode(Normal::FAIL,"订单已取消");
        }
        if($order['status']==10){
            return Normal::returnCode(Normal::FAIL,"订单未支付");
        }
        if($order['push_success']==0){
            return Normal::returnCode(Normal::FAIL,"订单未推送成功，请先推送订单");
        }
        //组装推送数据
        $data = PushAgain::instance()->info(['sn' => $param['sn']]);
        if(empty($data)){
            return Normal::returnCode(Normal::FAIL,"推送数据不存在");
        }
        $OrderCloudService=new OrderCloudService();
        $orderData=json_decode($data['pay_data'], true);
        $res2 = $OrderCloudService->sendToStoB($orderData, 'OrderPay');
        if ($res2['code'] != 200) {
            return Normal::returnCode(Normal::FAIL,'订单推送成功，但是云仓支付失败，失败原因：' . $res2['msg'] . ',请联系客服');
        }else{
            Order::instance()->edit(['id' => $order['id']], ['push_pay_success' => 1]);
            return Normal::returnCode(Normal::SUC,'推送成功');
        }
    }

    /**
     * 订单状态枚举
     */
    public function getOrderStatus()
    {
        $status=Order::instance()->status;
        $list=[];
        foreach ($status as $k=>$v){
            $item['status']=$k;
            $item['name']=$v;
            $list[]=$item;
        }
        return Normal::returnCode(Normal::SUC,"请求成功",$list);
    }

    /**
     * 接收云仓发货消息
     */
    public function OrderExpress($param)
    {
        try{
            $sn=$param['order_sn'];
            $order=Order::instance()->info(['sn'=>$sn]);
            if(empty($order)){
                $order=Order::instance()->info(['pay_sn'=>$sn]);
                if(empty($order)){
                    return [
                        'code'=>Normal::FAIL,
                        'msg'=>'订单不存在'
                    ];
                }
            }
            if($order['status']==0){
                return [
                    'code'=>Normal::FAIL,
                    'msg'=>'订单已取消'
                ];
            }
            if($order['status']>=30){
                return [
                    'code'=>Normal::SUC,
                    'msg'=>'订单已发货成功'
                ];
            }
            $orderGoods=OrderExtra::instance()->info(['order_id'=>$order['id'],'stb_sn'=>$param['hnOrderNo']]);
            if(empty($orderGoods)){
                return [
                    'code'=>Normal::FAIL,
                    'msg'=>'未找到订单'
                ];
            }
            $edit=[
                'express_num'=>$param['expressNo'],
                'express_name'=>$param['expressName'],
            ];
            OrderExtra::instance()->edit(['id'=>$orderGoods['id'],'stb_sn'=>$param['hnOrderNo']],$edit);
            $time=time();
            $auto_receive=$time+10*86400;
            Order::instance()->edit(['id'=>$order['id']],['status'=>30,'shipping_time'=>$time,'auto_receive'=>$auto_receive,'md'=>$time]);
            return [
                'code'=>Normal::SUC,
                'msg'=>'发货成功'
            ];
        }catch (\Exception $e){
            return [
                'code'=>Normal::FAIL,
                'msg'=>$e->getMessage()
            ];
        }
    }

    /**
     * 15分钟未支付，自动取消订单
     */
    public function noPayCancel()
    {
        $time = time() - 900;
        $where=[
            ['pay_status','=',0],
            ['pay_time','=',0],
            ['status','=',10],
            ['cd','<',$time],
            '_fields_'=>'sn,cid,id'
        ];
        $order = Order::instance()->lists($where);
        if ($order) {
            $OrderCloudService=new OrderCloudService();
            foreach ($order as $v) {
                $orderData = [
                    'orderSn' => $v['sn'],
                    'exceptReason' => '15分钟未支付，自动取消订单',
                    'cid' => $v['cid']
                ];
                $OrderCloudService->sendToStoB($orderData, 'OrderCancel');
                Order::instance()->edit(['id' => $v['id']], ['status' => 0, 'md' => time()]);
                //归还优惠券
//                if($v['coupon_id']>0){
//                    if($v['mnid']==4){
//                        $coupon=CouponUser::instance()->info(['mid'=>$v['mid'],'mn_sid'=>$v['mn_sid'],'coupon_id'=>$v['coupon_id'],'status'=>2,'sn'=>$v['sn']]);
//                        if($coupon){
//                            CouponUser::instance()->edit(['id'=>$coupon['id']],['sn'=>'','use_time'=>0,'status'=>1]);
//                            if($coupon['manual_id']>0){
//                                CouponManual::instance()->edit(['id'=>$coupon['manual_id']],['status'=>2,'use_time'=>0]);
//                            }
//                        }
//                    }else{
//                        $coupon=ChannelCouponUser::instance()->info(['mid'=>$v['mid'],'coupon_id'=>$v['coupon_id'],'status'=>2,'sn'=>$v['sn']]);
//                        if($coupon){
//                            ChannelCouponUser::instance()->edit(['id'=>$coupon['id']],['sn'=>'','use_time'=>0,'status'=>1]);
//                            if($coupon['manual_id']>0){
//                                ChannelCouponManual::instance()->edit(['id'=>$coupon['manual_id']],['status'=>2,'use_time'=>0]);
//                            }
//                        }
//                    }
//                }
                $log = [
                    'order_id' => $v['id'], 'order_status' => 0, 'msg' => '15分钟未支付，自动取消订单','time' => $time,'role'=>'系统'
                ];
                OrderLog::instance()->add($log);
            }
        }
    }

    /**
     * 自动收货
     */
    public function autoReceive()
    {
        $now = time();
        $where=[
            ['pay_status','=',1],
            ['status','=',30],
            ['auto_receive','<',$now],
        ];
        $order = Order::instance()->lists($where);
        if ($order) {
            foreach ($order as $v) {
                Order::instance()->edit(['id' => $v['id']], ['status' => 40, 'receive_time' => $now, 'md' => $now]);
                $log = [
                    'order_id' => $v['id'], 'order_status' => 40, 'msg' => '自动收货','time' => $now,'role'=>'系统'
                ];
                OrderLog::instance()->add($log);
                if ($v['cid'] > 0) {
                    $day=Commission::instance()->day;
                    $config=ConfigChannel::instance()->info(['code'=>'settle_bill_day','cid'=>$v['cid']]);
                    if(!empty($config)){
                        $value=json_decode($config['value'],1);
                        $day=$value['day']??Commission::instance()->day;
                    }
                    $time =$now + $day * 86400;
                    Commission::instance()->edit(['sn' => $v['sn']], ['thaw_time' => $time]);//店铺分佣
                }
            }
        }
    }


}

